package rjp.solver;

import java.util.Random;

import rjp.map.SantaMap;
import rjp.mutation.MakeALongestMutation;
import rjp.mutation.MoveSegmentMutation;
import rjp.solution.Solution;

public class RandomSegmentMoveSolver implements Solver {
	
	Solution solution;
	Random random;
	SantaMap map;
	int numberOfSteps=1000;
	
	public RandomSegmentMoveSolver(SantaMap map)
	{
		this.solution=(new OrderedSolver()).solve(map);
		this.random=new Random();
		this.map=map;
	}
	
	public RandomSegmentMoveSolver(SantaMap map, Solution startSolution)
	{
		this.solution=startSolution;
		this.random=new Random();
		this.map=map;
	}
	
	public void setNumberOfSteps(int steps)
	{
		this.numberOfSteps=steps;
	}

	@Override
	public Solution solve(SantaMap map) {
		for(int i=0; i<this.numberOfSteps; i++)
		{
			this.step();
			//System.out.println("Step "+i+" "+this.solution.getScore());
		}
		return this.solution;
	}
	
	private void align()
	{
		MakeALongestMutation mut=new MakeALongestMutation(this.map);
		mut.mutate(this.solution);
	}
	
	private void step()
	{
		MoveSegmentMutation mut=null;
		boolean error;
		do
		{
			error=false;
			try
			{
				mut=new MoveSegmentMutation((int) (this.random.nextFloat()*this.map.size()), 
						(int) (this.random.nextFloat()*this.map.size()),
						(int) (this.random.nextFloat()*this.map.size()), this.map);
			} catch(IllegalArgumentException e)
			{
				error=true;
			}
			
		} while(error);
	
		if(mut.solutionImprovement(this.solution)>=-0.1 && mut.isLegal(this.solution))
		{
			mut.mutate(solution);
			this.align();
		}
	}

}
